<?php
namespace App\Repository\Sys;

class OutPut
{


    private $filename;
    private $file;

    function __construct($filename = null)
    {
        if (!$filename) {
            $this->filename = '导出数据' . date('Y-m-d H:i:s').'.csv';
        } else {
            $this->filename = $filename;
        }

        $this->file = fopen('php://output', 'a');

        $this->start();

    }
    private function start()
    {
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
        header('Content-Disposition: attachment;filename=' . $this->filename);
        header('Cache-Control: max-age=0');
    }

    public function setHead($head)
    {
        foreach ($head as $i => $row) {
            $head[$i] = mb_convert_encoding($row, 'CP936', 'UTF-8');
        }
        fputcsv($this->file, $head);
    }

    public function setData($dataArray)
    {
        $outData = array();
        foreach ($dataArray as $k => $v) {
            array_push($outData, mb_convert_encoding($v, 'CP936', 'UTF-8'));
        }

        fputcsv($this->file, $outData);
    }

    public function end()
    {
        fclose($this->file);
        exit;
    }


    public static function out($file_name, $head, $content)
    {
        $file_name = str_replace(',',' ', $file_name);
        $file_name = str_replace('，',' ', $file_name);
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
        header('Content-Disposition: attachment;filename=' . $file_name);
        header('Cache-Control: max-age=0');

        // 打开PHP文件句柄，php://output 表示直接输出到浏览器
        $fp = fopen('php://output', 'a');

        //转码 否则 excel 会乱码
        foreach ($head as $i => $row) {
            $head[$i] = mb_convert_encoding($row, 'CP936', 'UTF-8');
        }

        fputcsv($fp, $head);

        foreach ($content as $tent) {
            $outData = array();
            foreach ($tent as $k => $v) {
                array_push($outData, mb_convert_encoding($v, 'CP936', 'UTF-8'));
            }
            fputcsv($fp, $outData);
        }
        exit;
    }

}